﻿using SAEA.Common;
using SAEA.MVC;
using KeydbCommand.Libs;
using System;

namespace KeydbCommand
{
    class Program
    {
        static int Main(string[] args)
        {
            int Port = 8080;
            if (args.Length > 0)
            {
                var argChars = string.Join(" ", args);
                if (argChars == "-v" || argChars == "--version")
                {
                    Console.WriteLine("KeydbCommand {0}",Constants.Version);
                    return 0;
                }
                if (argChars == "-h" || argChars == "--help")
                {
                    Console.WriteLine("Please Input:\nKeydbCommand -p [port]\nKeydbCommand --port=[port]");
                    return 0;
                }
                if (args.Length == 1 && args[0].Contains("--port="))
                {
                    var arg = args[0].Remove(0, 7);
                    if (int.TryParse(arg, out var port))
                    {
                        if(port > short.MaxValue)
                        {
                            Console.WriteLine("ERROR: Port MaxValue:[65535]");
                            return 1;
                        }
                        Port = port;
                    }
                    else
                    {
                        Console.WriteLine("ERROR: Port error:[0-65535]");
                        return 1;
                    }
                }

                if (args.Length == 2 && args[0] == "-p")
                {
                    if (int.TryParse(args[1], out var port))
                    {
                        if(port > short.MaxValue)
                        {
                            Console.WriteLine("ERROR: Port MaxValue:[65535]");
                            return 1;
                        }
                        Port = port;
                    }
                    else
                    {
                        Console.WriteLine("ERROR: Port error:[0-65535]");
                        return 1;
                    }
                }
            }

            ConsoleHelper.Title = "KeydbCommand " + Constants.Version;

            var config = SAEAMvcApplicationConfigBuilder.Read();

            config.Port = Port;

            //config.IsStaticsCached = false;

            SAEAMvcApplicationConfigBuilder.Write(config);

            //启动api

            SAEAMvcApplication mvcApplication = new SAEAMvcApplication(config);

            mvcApplication.Start();

            ConsoleHelper.WriteLine("KeydbCommand Already started");

            ConsoleHelper.WriteLine($"Please open on Browser：http://127.0.0.1:{config.Port}/");

            ConsoleHelper.WriteLine("Enter to exit service...");

            while (true)
            {
                ThreadHelper.Sleep(5000);
            }
        }
    }
}
